package buka.oversea.aeron5.controller;

import buka.oversea.aeron5.service.BalanceClusteredService;
import io.aeron.cluster.client.AeronCluster;
import org.agrona.concurrent.UnsafeBuffer;
import org.springframework.web.bind.annotation.*;

import java.nio.ByteBuffer;

@RestController
@RequestMapping("/api/balance")
public class BalanceController {

    private final BalanceClusteredService service;
    private final AeronCluster clusterClient;

    public BalanceController(BalanceClusteredService service, AeronCluster clusterClient) {
        this.service = service;
        this.clusterClient = clusterClient;
    }

    @GetMapping("/{account}")
    public Long balance(@PathVariable String account) {
        return service.balance(account);
    }

    @PostMapping("/{account}/add/{amount}")
    public Long add(@PathVariable String account, @PathVariable long amount) throws Exception {
        return sendCommand((byte) 0, account, amount);
    }

    @PostMapping("/{account}/sub/{amount}")
    public Long sub(@PathVariable String account, @PathVariable long amount) throws Exception {
        return sendCommand((byte) 1, account, amount);
    }

    private Long sendCommand(byte op, String account, long amount) throws Exception {
        UnsafeBuffer buf = new UnsafeBuffer(ByteBuffer.allocate(1 + 8 + account.length()));
        buf.putByte(0, op);
        buf.putLong(1, amount);
        buf.putStringAscii(9, account);

        // 同步阻塞示例：生产请用异步 poll
        long correlationId = clusterClient.offer(buf, 0, buf.capacity());
        // 这里略去 poll response，仅演示，实际需轮询
        return 0L;
    }
}
